<template>
    <a-form ref='formRef' laylayout="vertical" :label-col='{span : 5}' :model='formData'>
        <a-form-item style='display:none' name='id'>
            <a-input type='hidden' v-model:value='formData.id' />
        </a-form-item>
        <a-form-item label='链名称' name='name' :rules="[{required : true, message : '请填写链名称'}]">
            <a-input type='text' v-model:value='formData.name' />
        </a-form-item>
        <a-form-item label='标识名称' name='markName' :rules="[{required : true, message : '请填写标识名称'}]">
            <a-input type='text' v-model:value='formData.markName' />
        </a-form-item>
        <a-form-item label='链core' name='chainCore' :rules="[{required : true, message : '请填写链core'}]">
            <a-input-number type='number' :min="0" :max="2000000" v-model:value.number='formData.chainCore' />
        </a-form-item>
        <a-form-item label='网络ID' name='networkId' :rules="[{required : true, message : '请填写网络ID'}]">
            <a-input-number type='number' :min="0" :max="2000000" v-model:value.number='formData.networkId' />
        </a-form-item>
        <a-form-item label='Symbol' name='mainSymbol' :rules="[{required : true, message : '请填写Symbol'}]">
            <a-input type='text' v-model:value='formData.mainSymbol' />
        </a-form-item>
        <a-form-item label='Decimals' name='mainDecimals' :rules="[{required : true, message : '请填写Decimals'}]">
            <a-input-number type='number' :min="0" :max="255" v-model:value.number='formData.mainDecimals' />
        </a-form-item>
        <a-form-item label='币名称' name='mainCoinName' :rules="[{required : true, message : '请填写币名称'}]">
            <a-input type='text' v-model:value='formData.mainCoinName' />
        </a-form-item>
        <a-form-item label='费用估算模式' name='feeEstimatedMode' :rules="[{required : true, message : '请填写费用估算模式'}]">
            <a-input type='text' v-model:value='formData.feeEstimatedMode' />
        </a-form-item>
        <a-form-item label='默认Gas价格预言机' :label-col="{span : 24}" name='defaultGasOracle'>
            <a-space>
                <a-form-item label='safe' :label-col="{span : 10}" :name="['defaultGasOracle', 'safe']">
                    <a-input type='text' v-model:value='formData.defaultGasOracle.safe' />
                </a-form-item>
                <a-form-item label='propose' :label-col="{span : 10}" :name="['defaultGasOracle', 'propose']">
                    <a-input type='text' v-model:value='formData.defaultGasOracle.propose' />
                </a-form-item>
                <a-form-item label='fast' :label-col="{span : 10}" :name="['defaultGasOracle', 'fast']">
                    <a-input type='text' v-model:value='formData.defaultGasOracle.fast' />
                </a-form-item>
            </a-space>
        </a-form-item>
        <a-form-item label='节点设置' :label-col="{span : 24}" name='endpoints'>
            <div>
                <a-space v-for="(item, index) in formData.endpoints" :key="index">
                    <a-form-item label='节点名称' :name="['endpoints', index, 'nodeName']" :rules="[{required : true, message : '请填写节点名称'}]">
                        <a-input type='text' v-model:value='formData.endpoints[index].nodeName' />
                    </a-form-item>
                    <a-form-item label='节点URL' :name="['endpoints', index, 'nodeURL']" :rules="[{required : true, message : '请填写节点URL'}]">
                        <a-input type='text' v-model:value='formData.endpoints[index].nodeURL' />
                    </a-form-item>
                    <a-form-item><MinusCircleOutlined style="cursor: pointer;" v-if="formData.endpoints.length > 1" @click="removeEndpoints(index)" /></a-form-item>
                </a-space>
                <div style="padding-left: 13%">
                    <div>
                        <a-button type="dashed" style="width: 50%" @click="addEndpoints"><PlusOutlined /></a-button>
                    </div>
                </div>
                
            </div>
        </a-form-item>

        
        <a-form-item label='logo' name='logoUrl'>
            <a-upload list-type='picture-card' :max-count="1" v-model:file-list='coverList' :beforeUpload='beforeUpload' :customRequest='uploadCover' accept="image/png,image/jpeg,image/gif,image/webp,image/svg+xml">
                <template v-if='coverList.length == 0'>
                    <PlusOutlined />
                </template>
            </a-upload>
        </a-form-item>
        <a-form-item label='币logo' name='coinLogoUrl'>
            <a-upload list-type='picture-card' :max-count="1" v-model:file-list='coinCoverList' :beforeUpload='beforeUpload' :customRequest='uploadCoinCover' accept="image/png,image/jpeg,image/gif,image/webp,image/svg+xml">
                <template v-if='coinCoverList.length == 0'>
                    <PlusOutlined />
                </template>
            </a-upload>
        </a-form-item>
        <a-form-item label='modules' name='modules' :rules="[{required : true, message : '请填写modules'}]">
            <a-textarea v-model:value="formData.modules" placeholder="可换行输入多个" :rows="4" />
        </a-form-item>
        <a-form-item label='资源服务器' name='resourcesServicesURL'>
            <a-input type='text' v-model:value='formData.resourcesServicesURL' />
        </a-form-item>
        <a-form-item label='区块浏览器' name='scanURL'>
            <a-input type='text' v-model:value='formData.scanURL' />
        </a-form-item>
        <a-form-item label='区块浏览器api key' name='scanAPIKey'>
            <a-input type='text' v-model:value='formData.scanAPIKey' />
        </a-form-item>
        <a-form-item label='排序' name='sort'>
            <a-input type='number' v-model:value='formData.sort' />
        </a-form-item>
        <a-form-item label='启用' name='enable'>
            <a-switch v-model:checked='formData.enable' checked-children='启用' un-checked-children='禁用'/>
        </a-form-item>
    </a-form>
</template>

<script lang="ts" setup>
    import { saveApi } from '@/api/Chain';
import { uploadIconApi } from '@/api/Upload';
        import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { Modal } from 'ant-design-vue';
        import { nextTick, ref } from 'vue';


    const props = defineProps<{
        row? : any;
    }>()

    const coverList = ref<any[]>([])
    const coinCoverList = ref<any[]>([])

    const formRef = ref()

    
    const formData = ref<any>({
        id : 0,
        "name": "",
        "markName": "",
        "chainCore": '',
        "networkId": '',
        "mainSymbol": "",
        "mainDecimals": '',
        "mainCoinName": "",
        "logoUrl": "",
        "coinLogoUrl": "",
        "feeEstimatedMode": "",
        "defaultGasOracle": {
            "safe": "",
            "propose": "",
            "fast": ""
        },
        "selectEndpointIndex": '',
        "endpoints": [],
        "modules": [],
        "source": "",
        "resourcesServicesURL": "",
        "scanURL": "",
        "scanAPIKey": "",


        sort : 1,
        enable : true

    })

    function addEndpoints() {
        formData.value.endpoints.push({
            "nodeURL": "",
            "nodeName": "",
            "type": 0
        })
    }

    function removeEndpoints(index:number) {
        Modal.confirm({
            title : '确定删除吗',
            onOk() {
                formData.value.endpoints.splice(index, 1)
            }
        })
    }

    if(props.row) {
        for(let k in props.row) {
            if(k in formData.value) {
                if(k == 'modules') {
                    formData.value[k] = props.row[k].join("\n")
                }else {
                    formData.value[k] = props.row[k]
                }
                
            }
        }
        if(props.row.logoUrl) {
            coverList.value[0] = {
                status : 'done',
                url : import.meta.env.B_NET_STATIC_URL + props.row.logoUrl
            }
        }
        if(props.row.coinLogoUrl) {
            coinCoverList.value[0] = {
                status : 'done',
                url : import.meta.env.B_NET_STATIC_URL + props.row.coinLogoUrl
            }
        }

        
    }else {
        addEndpoints()
    }

    async function submit() {
        let params  = await formRef.value.validate()
        
        if('sort' in params && params.sort === '') {
            params.sort = 1
        }

        params.modules = params.modules.split('\n')




        return saveApi(params)
    }


    function uploadCover(e) {
        if(e.file.size > 100 * 1024) {
            Modal.error({
                title : '图标不能大于100kb'
            })
            coverList.value = []
            return false
        }


        uploadIconApi(e.file).then(res => {
            coverList.value[0].status = 'done'
            coverList.value[0].url = import.meta.env.B_NET_STATIC_URL + res.data
            formData.value.logoUrl = res.data
        })
    }

    function uploadCoinCover(e) {
        if(e.file.size > 100 * 1024) {
            Modal.error({
                title : '图标不能大于100kb'
            })
            coinCoverList.value = []
            return false
        }


        uploadIconApi(e.file).then(res => {
            coinCoverList.value[0].status = 'done'
            coinCoverList.value[0].url = import.meta.env.B_NET_STATIC_URL + res.data
            formData.value.coinLogoUrl = res.data
        })
    }

    function beforeUpload(file:File, field:FormField) {
        return true
    }


    defineExpose({
        submit
    })
</script>